package com.newly.gateway.filter;

import com.newly.common.base.constants.AuthConstant;
import com.newly.common.base.constants.CodeConstant;
import com.newly.common.base.constants.ServerUriConstant;
import com.newly.common.base.entity.R;
import com.newly.gateway.service.api.ICheckService;
import com.newly.gateway.utils.ResponseUtil;
import com.newly.profile.property.SysProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author gjm guan
 * @date 2021/9/3 16:15
 * @desc 检测token合法性与放行路劲等
 */
@Slf4j
@Configuration
public class CheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private ICheckService checkService;

    @Autowired
    private SysProperties sysProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        RequestPath path = request.getPath();

        // 放行所有options请求
        if (request.getMethod().name().equalsIgnoreCase("OPTIONS")) {
            return chain.filter(exchange);
        }

        // 处理登录请求
        if (path.value().contains(ServerUriConstant.NEWLY_AUTH_LOGIN)) {
            boolean result = checkService.validateCaptcha(exchange);
            if (!result) {
                return ResponseUtil.write(exchange, HttpStatus.OK, R.fail("验证码错误！"));
            }
        }

        // 检测是否放行请求
//        if (handleSysService.isOpenPath(request.getPath().value())) {
//            return chain.filter(exchange);
//        }
        if (true) {
            return chain.filter(exchange);
        }
        // 结合redis校验token
        String requestToken = request.getHeaders().getFirst(AuthConstant.JWT_TOKEN_KEY);


        // 说明token无效，抛出401状态码
        return ResponseUtil.write(exchange, HttpStatus.OK,
                R.fail(CodeConstant.AUTH_ERR, "未授权，请检查登录！"));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
